from django.contrib import admin

# Register your models here.
from goods import models
from celery_tasks.static_html.tasks import generate_static_list_search_html, generate_static_sku_detail_html
from goods.models import Goods, SKU, SKUImage


class GoodsCategoryAdmin(admin.ModelAdmin):
    """增加功能，后台修改数据就进行静态页面自动刷新"""

    def save_model(self, request, obj, form, change):
        obj.save()
        generate_static_list_search_html.delay()

    def delete_model(self, request, obj):
        obj.delete()
        generate_static_list_search_html.delay()


class SKUAdmin(admin.ModelAdmin):
    def save_model(self, request, obj, form, change):
        obj.save()
        generate_static_sku_detail_html.delay(obj.id)


class SKUSpecificationAdmin(admin.ModelAdmin):
    def save_model(self, request, obj, form, change):
        obj.save()
        from celery_tasks.static_html.tasks import generate_static_sku_detail_html
        generate_static_sku_detail_html.delay(obj.sku.id)

    def delete_model(self, request, obj):
        sku_id = obj.sku.id
        obj.delete()
        from celery_tasks.static_html.tasks import generate_static_sku_detail_html
        generate_static_sku_detail_html.delay(sku_id)


class SKUImageAdmin(admin.ModelAdmin):
    def save_model(self, request, obj, form, change):
        obj.save()
        from celery_tasks.static_html.tasks import generate_static_sku_detail_html
        generate_static_sku_detail_html.delay(obj.sku.id)

        # 设置SKU默认图片
        sku = obj.sku
        if not sku.default_image_url:
            sku.default_image_url = obj.image.url
            sku.save()

    def delete_model(self, request, obj):
        sku_id = obj.sku.id
        obj.delete()
        from celery_tasks.static_html.tasks import generate_static_sku_detail_html
        generate_static_sku_detail_html.delay(sku_id)


# Register your models here.
admin.site.register(Goods, GoodsCategoryAdmin)
admin.site.register(SKU, SKUAdmin)
admin.site.register(SKUImage, SKUImageAdmin)
